<template>
	<view class="container">
		<view class="inputIsbn">
			
				<!-- <uni-easyinput v-model="book.bookName" placeholder="请输入书名" /> -->
				<uni-easyinput maxlength="50" v-model="isbn" placeholder="请输入ISBN查询" />
				<button type="primary" @click="searchISBN(isbn)">查询</button>
			
		</view>
		
		<view class="example">
			<uni-forms ref="form" :model="scanData" labelWidth="80px">
				<uni-forms-item label="图书名称" name="bookName">
					<!-- <uni-easyinput v-model="book.bookName" placeholder="请输入书名" /> -->
					<uni-easyinput v-model="mysqlData.name" placeholder="请输入书名" />
				</uni-forms-item>
				<uni-forms-item label="作者" name="author">
					<uni-easyinput v-model="scanData.author" placeholder="请输入作者" />
				</uni-forms-item>

				<!-- <uni-forms-item label="分类" name="category">
					<view class="category">
						<checkbox-group @change="handleChange" >
							
							<label v-for="(item,index) in categoryList" :key="index">
								<checkbox :value="item.value" :checked="false" />{{item.name}}
							</label>

						</checkbox-group>
					</view>
				</uni-forms-item> -->


				<uni-forms-item label="出版社" name="press">
					<uni-easyinput @blur="searchOrAddPublish" v-model="scanData.press" placeholder="请输入出版社" />
				</uni-forms-item>
				<uni-forms-item label="ISBN" name="ISBN">
					<uni-easyinput v-model="scanData.isbn" placeholder="请输入ISBN" />
				</uni-forms-item>

				<uni-forms-item label="介绍" name="introduction">
					<uni-easyinput v-model="scanData.bookDesc" placeholder="请输入简介" />
				</uni-forms-item>

				<!-- 语言选择器 -->
				<!-- <uni-forms-item label="语言" name="language">
					<picker @change="bindPickerChange" :value="index" :range="array" range-key="name">
						<view style="padding: 20rpx;background-color: white;">{{ array[index].name }}</view>
					</picker>
				</uni-forms-item> -->

				<!-- <uni-forms-item label="语言" name="language">
					<uni-easyinput @blur="searchOrAddLanguage" v-model="scanData.language" placeholder="请输入语言" />
				</uni-forms-item> -->



				<uni-forms-item label="价格" name="price">
					<uni-easyinput v-model="mysqlData.price" placeholder="请输入价格" />
				</uni-forms-item>

				<uni-forms-item label="数量" name="number">
					<uni-easyinput v-model="book.number" placeholder="请输入数量" />
				</uni-forms-item>

				<uni-forms-item  label="位置" name="location">
					<uni-easyinput disabled v-model="book.location" placeholder="请输入位置" />
				</uni-forms-item>

			
			</uni-forms>
			<button type="primary" @click="handleEdit">修改</button>
		</view>
	</view>
</template>

<script>
	import storage from '@/utils/storage'
	import {
		getToken
	} from '../../utils/auth.js'
	import {
		getUserProfile
	} from "@/api/system/user"
	import {
		updateUserProfile
	} from "@/api/system/user"
	import {
		// addBook,
		getAuthorId,
		getPublishId,
		getLanguageId,
		addAuthorId,
		addPublishId,
		addLanguageId,
		getCategoryList,
		addBook,
		editBook
	} from "@/api/index/index"
	import {getBookInfo} from '@/api/work/work.js';
	
import { type } from "os"
	export default {
		data() {
			return {
				isbn:'',//输入框isbn
				categoryList: [], //分类数据源
				mysqlData:{},//后端查到的数据
				scanData: { //扫描数据源
					bookName: "",
					author: "",
					press: "",
					isbn: "",
					bookDesc: "",
					language: "1",
					price: "",
					number: "",
					location: "",
					createBy: "1",
					categoryId: "",
					url: "",
					createTime: ""
				},
				book: {//提交的表单数据
					// name: "",
					author: "",
					publish: "",
					isbn: "",
					introduction: "",
					// language: "",
					// price: "199",
					number: "1",
					location: "未上架",
					createBy: "1",
					categoryId: "1",
					url: "",
					isDelete:"0",
					createTime: "",
					updateBy:"0"
				},
				
				rules: {
					bookName: {
						rules: [{
							required: true,
							errorMessage: '书名不能为空'
						}]
					},

					language: {
						rules: [{
							required: true,
							errorMessage: '语言不能为空'
						}]
					},

			

					price: {
						rules: [{
							required: true,
							errorMessage: '价格不能为空'
						}]
					},
					isbn: {
						rules: [{
							required: true,
							errorMessage: 'ISBN不能为空'
						}]
					},
					author: {
						rules: [{
							required: true,
							errorMessage: '作者不能为空'
						}]
					},
					press: {
						rules: [{
							required: true,
							errorMessage: '出版社不能为空'
						}]
					}
				}
			}
		},
		onLoad(option) {
			this.getUser()
			// this.scanData = JSON.parse(decodeURIComponent(option.scanData));
			// 进入页面请求分类数据
			getCategoryList({
				type: "category"
			}).then(res => {
				this.categoryList = res.data
				console.log("分类数据源", this.categoryList);
			})
			
			// console.log("scanData",option.scanData);
			// console.log("isbn",option.isbn);
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},

		methods: {
			//查询isbn的信息
			searchISBN(isbn){
				console.log("查询isbn",this.isbn);
				//第三方查询数据
				uni.request({
					url:`http://openapi.daohe168.com.cn/api/library/isbn/query?isbn=${isbn}&appKey=d7c6c07a0a04ba4e65921e2f90726384`,
					method:"GET",
				}).then(resp => {
					//第一个api超过每日使用限制切换其他api
					if(resp[1].data.data == null){
						 	uni.request({
								url: "http://data.isbn.work/openApi/getInfoByIsbn?appKey=ae1718d4587744b0b79f940fbef69e77",
								method: "GET",
								data: {
									isbn: this.isbn
								},
								header: {
									'Authorization': 'Bearer ' + getToken()
								}
							}).then(resp => {
								console.log("执行了第二种api",resp[1].data.data)
								this.scanData = resp[1].data.data
							})
					}
					console.log("第三方查询到的数据",resp[1].data.data);
					this.scanData = resp[1].data.data
				})
				//向数据库查询信息
				getBookInfo({pageNum:1,pageSize:10,searchByName:this.isbn}).then(res=>{
					// console.log("向数据库查到的信息",res.rows[0]);
					this.mysqlData = res.rows[0]
					console.log("向数据库查到的信息",this.mysqlData);
				}).catch(err=>{
					console.log("数据库查询信息接口失败");
				})
				
				
			},
			handleChange(e){
				if(e.detail.value.join(',') != ''){
					this.book.categoryId = e.detail.value.join(',')
				}
				console.log(e.detail.value.join(','));
				// console.log(typeof(e.detail.value));
			},
			//分类多选框
			showCategory() {

				uni.showActionSheet({
					itemList: ['A', 'B', 'C'],
					success: function(res) {
						console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},

			//处理提交时间函数
			handleTime() {
				// 创建一个 Date 对象
				var today = new Date();

				// 获取年、月、日、时、分、秒
				var year = today.getFullYear();
				var month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
				var day = today.getDate();
				var hours = today.getHours();
				var minutes = today.getMinutes();
				var seconds = today.getSeconds();

				// 格式化输出
				var formattedTime = year + "-" +
					(month < 10 ? "0" : "") + month + "-" +
					(day < 10 ? "0" : "") + day + " " +
					(hours < 10 ? "0" : "") + hours + ":" +
					(minutes < 10 ? "0" : "") + minutes + ":" +
					(seconds < 10 ? "0" : "") + seconds;
				this.book.createTime = formattedTime

				// console.log(this.addForm.createTime);
				// "2023-11-08 19:05:05"
			},

			// 查询作者id无则添加作者
			searchOrAddAuthor() {
				console.log("查询作者id中...");
				//后端 查询作者id号
				getAuthorId({
					"type": "author",
					"keyWord": this.scanData.author
				}).then(res => {
					// 查询不到id号
					console.log("作者", res);
					if (res.data.length === 0) {
						console.log("作者id未查到，执行添加");
						// 添加作者接口
						addAuthorId({
							"value": [this.scanData.author],
							"type": "author"
						}).then(res => {
			
							this.book.author = String(res.data)
							console.log("返回的作者id是", res.data);
						}).catch(err => {
							console.log("添加作者号错误");
						})
					} else {
						this.book.author = res.data[0].authorValue
					}
				})
			},

			// 查询出版社id无则添加出版社
			searchOrAddPublish() {
				//后端 查询出版社id号
				getPublishId({
					"type": "publish",
					"keyWord": this.scanData.press
				}).then(res => {
					// 查询不到id号
					if (res.data.length === 0) {
						console.log("出版社号查询失败");
						// 添加出版社接口
						addAuthorId({
							"value": [this.scanData.press],
							"type": "publish"
						}).then(res => {

							this.book.publish = String(res.data)
							console.log("新增出版社号成功", res.data);
						}).catch(err => {
							console.log("添加出版社号错误");
						})
					} else {
						this.book.publish = res.data[0].publishValue
						console.log("出版社",res);
					}
				})
			},

			// 查询语言id无则添加语言
			searchOrAddLanguage() {
				//后端 查询语言id号
				getPublishId({
					"keyWord": this.scanData.language,
					"type": "language"
				}).then(res => {
					console.log("查询到的语言id",res);
					// 查询不到id号
					if (res.data.length === 0) {
						// 添加语言接口
						addAuthorId({
							"value": [this.scanData.language],
							"type": "language"
						}).then(res => {
							this.book.language = String(res.data)
						}).catch(err => {
							console.log("添加语言错误");
						})
					} else {
					
						this.book.language = res.data[0].languageValue
					}
				})
			},

			getUser() {
				getUserProfile().then(response => {
					this.user = response.data
				})
			},
			// // 查询作者id
			// click_author() {
			// 	console.log("执行了查询作者 id");
			// 	getAuthorId({
			// 			"dictAuthor": this.scanData.author,
			// 			"dictType": "sys_book_author"
			// 		})
			// 		.then(res => {
			// 			console.log("查询的作者id结果:", res);
			// 		}).catch(err => {
			// 			console.log(err);
			// 		})
			// },
			// 修改书籍
			handleEdit(ref) {
				this.searchOrAddAuthor(),
					this.searchOrAddPublish(),
					// this.searchOrAddLanguage(),
					this.handleTime()
				this.book.language = "0"
				// this.searchOrAddLanguage(),
				// this.book = this.scanData
				// console.log("提交的scandata:", this.scanData);
				this.book.name = this.mysqlData.name,
					this.book.isbn = this.scanData.isbn,
					this.book.introduction = this.scanData.bookDesc,
					this.book.price = this.mysqlData.price,
					this.book.bookId = this.mysqlData.bookId
					this.book.url = this.scanData.pictures.split('"')[1]
				this.book.number = "1",
				this.$refs.form.validate().then(res => {
					console.log("提交的信息", this.book);
					
					setTimeout(() => {
						editBook(this.book).then(res => {
							console.log(res);
							uni.switchTab({
								url:'/pages/mine/index',
								
							})
						}).catch(err => {
							console.log("修改书籍失败");
						})
					}, 500)
					
				})

			}
		}
	}
</script>

<style lang="scss">
// isbn输入框样式
.inputIsbn{
	display: flex;
	justify-content: space-between;
}

	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}

	//分类框
	.category{
		border: 1px solid gray;
	}
	
	.uni-list-cell {
		justify-content: flex-start
	}
</style>